import 'package:json_annotation/json_annotation.dart';

part 'recipe_favorite_list_api.g.dart';

@JsonSerializable()
class ResponseRecipeFavoriteListApi {
  final int total;
  final List<RecipeFavorite> rows;

  ResponseRecipeFavoriteListApi({required this.total, required this.rows});

  factory ResponseRecipeFavoriteListApi.fromJson(Map<String, dynamic> json) =>
      _$ResponseRecipeFavoriteListApiFromJson(json);

  Map<String, dynamic> toJson() => _$ResponseRecipeFavoriteListApiToJson(this);
}

@JsonSerializable()
class RecipeFavorite {
  final String collectTime;
  final String id;
  final String name;
  final String? mainImg;
  final String? imageUrls;
  final String? videoCoverUrls;
  final String? view;
  final String? likes;
  final String? collection;
  final int? isControl;

  RecipeFavorite({
    required this.id,
    required this.name,
    required this.imageUrls,
    required this.videoCoverUrls,
    required this.collectTime,
    this.mainImg,
    this.view,
    this.likes,
    this.collection,
    this.isControl,
  });

  factory RecipeFavorite.fromJson(Map<String, dynamic> json) {
    final info = json['remoteRecipeMenuInfoVo'] ?? {};
    return RecipeFavorite(
      collectTime: json['collectTime'] ?? '',
      id: info['id'] ?? '',
      name: info['name'] ?? '',
      imageUrls: info['imageUrls'] ?? '',
      videoCoverUrls: info['videoCoverUrls'] ?? '',
      mainImg: _getImageUrl(info) ?? '',
      view: info['view'],
      likes: info['likes'],
      collection: info['collection'],
      isControl: info['isControl'],
    );
  }

  static String? _getImageUrl(Map<dynamic, dynamic> json) {
    final Map<String, dynamic> safeJson = Map<String, dynamic>.from(json);
    if (safeJson['mainImg'] != null && safeJson['mainImg'] is String) {
      String mainImg = safeJson['mainImg'];
      if (mainImg.isNotEmpty) return mainImg;
    }

    if (safeJson['imageUrls'] != null && safeJson['imageUrls'] is String) {
      String imageUrls = safeJson['imageUrls'];
      if (imageUrls.isNotEmpty) return imageUrls.split(',').first;
    }

    if (safeJson['videoCoverUrls'] != null &&
        safeJson['videoCoverUrls'] is String) {
      String imageUrls = safeJson['videoCoverUrls'];
      if (imageUrls.isNotEmpty) return imageUrls.split(',').first;
    }

    return null;
  }
}
